package cn.cloudreal.cbms.contract.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.GetFileSizes;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.contract.service.ContractListService;
import cn.cloudreal.cbms.log.service.OptLogService;
import cn.cloudreal.cbms.system.service.OrganizaService;
import cn.cloudreal.cbms.system.service.UserInfoService;
import cn.cloudreal.cbms.vo.Contract;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Log;
import cn.cloudreal.cbms.vo.MediaPrice;
import cn.cloudreal.cbms.vo.Organiza;
import cn.cloudreal.cbms.vo.UserInfo;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: ITC合同库
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author xiayundong
 * @date 2012-8-21
 */
public class ContractListAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	/**
	 * 返回树形菜单字符串
	 */
	private String flag;
	private String organizeValue; // 部门科室显示的value
	/**
	 * 搜索条件
	 */
	private String years; // 获取年份
	private String contractLevel; // 签约级别
	private String contractCity; // 归属地市
	private String contractOrganize; // 部门科室
	/** 当前页 */
	private int currentPage;
	/** 分页对象 */
	private PageBean page;

	/**
	 * 判断初次进入的状态
	 */
	private String type;

	/**
	 * 上传和下载
	 */
	private File inputfile;
	private String inputfileFileName;
	private String inputfileContentType;
	private String fileName; // 下载文件名
	private File file; // 下载文件
	/** 输入流 */
	private InputStream downloadStream;

	/**
	 * 各个页面的保存类
	 */
	private Contract contract; // 合同表类
	private Contract contractDetail;// 合同详情
	private Contract contractModify;// 合同修改
	private Contract contractUpdataModify; // 保存修改

	private String contractFileSize;// 合同文件的大小
	private Integer conuml; // 媒体后面显示的列数
	private String nowDate; // 获取当期的日期
	private String contractID;// 合同编号
	private String inputKeyword;// 关键字
	private int keyword; // 关键字下拉菜单

	private String contractDepartmentName;// 获取部门科室的中文名字
	private String contractCitycode; // 获取地市的cityCode
	private String toType; // 用户判断详情中的返回

	/**
	 * 注入service 类
	 */
	private OrganizaService organizaService = null;
	private ContractListService contractListService = null;
	private OptLogService optLogService = null; // 日志的service
	private UserInfoService userInfoService = null; // 用户表

	/**
	 * list
	 */
	private List<Contract> list = null; // 用于保存从数据库取出后的list对象数据
	private List<Contract> yearsList = null; // 用于保存每一年度的list数据
	private List<Dictionary> dataListGYSLX = null;// 供应商类型
	private List<Dictionary> dataListHTLX = null; // 合同类型
	private List<Dictionary> dataListQYJB = null; // 签约级别
	private List<Dictionary> dataListCITY = null; // 归属地市
	private List<Dictionary> dataListFKFS = null; // 付款方式
	private List<Organiza> organizaLists = null; // 组织架构
	private List<UserInfo> dataListUSER = null; // 签约人的
	private List<Log> logList = null; // 列表显示详情日志
	private List<String> listMediaName; // 媒体名称
	private List<MediaPrice> listMediaPrice; // 媒体价格表

	/** 日志工具类实例 */
	private static final Logger log = Logger
			.getLogger(ContractListAction.class);

	/*
	 * 获取所有合同列表，并分页显示
	 */
	public String findAllContractList() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction findAllContractList() method, return String");
		}

		try {
			if (null == years || "".equals(years)) {
				years = this.getYear();
			}
			yearsList = new ArrayList<Contract>();
			int yeares = Integer.parseInt(this.getYear());
			yeares = yeares + 1;
			for (int i = 0; i < 5; i++) {
				yeares = yeares - 1;
				Contract contractyear = new Contract();
				contractyear.setContractYear(String.valueOf(yeares));// values
				yearsList.add(contractyear);
			}
			Contract contractlist = new Contract();
			contractlist.setContractYear(years);

			getDictionary(); // 获取字典表中的数据

			// 获取userSession
			UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
					.getSession().getAttribute("logUser");
			String range = null;
			String cityCode = null;
			range = userSession.getUserRole().getRoleRange() == null ? ""
					: userSession.getUserRole().getRoleRange();
			cityCode = userSession.getUsercity() == null ? "" : userSession
					.getUsercity();
			// 设置权限
			if (null == type) {
				type = "1";
				contractCity = cityCode;
			}
			if ("1".equals(range)) {
			} else {
				dataListCITY = DatadicContext.getInstance()
						.getDicDataListByCode("CITY");// 归属地市
				dataListCITY.clear();
				Dictionary date = DatadicContext.getInstance()
						.getDatadicObject(cityCode, "CITY");
				dataListCITY.add(date);
				contractCity = cityCode;
			}

			// 搜索条件
			if (keyword == 0) {
				if (null == inputKeyword) {
					inputKeyword = "输入关键字搜索";
				}
			}
			if (keyword == 1) {
				if (inputKeyword.equals("输入关键字搜索")) {
					contractlist.setContractBName(""); // 按供应商名称
				} else {
					contractlist.setContractBName(inputKeyword); // 按供应商名称
				}
			}
			if (keyword == 2) {
				if (inputKeyword.equals("输入关键字搜索")) {
					contractlist.setContractOffice("");// 签约人
				} else {
					contractlist.setContractOffice(inputKeyword);// 签约人
				}

			}
			if (keyword == 3) {
				if (inputKeyword.equals("输入关键字搜索")) {
					contractlist.setContractName("");// 合同名称
				} else {
					contractlist.setContractName(inputKeyword);// 合同名称
				}

			}
			if (null != contractLevel && !"".equals(contractLevel)) {
				if (!contractLevel.equals(0)) {
					contractlist.setContractLevel(contractLevel);
				} // 签约级别
			}
			if (null != contractOrganize && !"".equals(contractOrganize)) {
				if (!contractOrganize.equals("--部门科室--")) {
					String orgName = getOrganize(contractOrganize);
					organizeValue = orgName;
					contractlist.setContractDepartment(contractOrganize);
				}
			}
			if (null == organizeValue || "".equals(organizeValue)) {
				organizeValue = "--部门科室--";
			}
			if (null != contractCity && !"".equals(contractCity)) {
				if (!contractCity.equals(0)) {
					contractlist.setContractCity(contractCity);
				} // 归属地市
			}

			/*
			 * 根据当前的地市来选择组织架构
			 */
			// 查询组织架构信息 获取当前节点集合
			organizaLists = new ArrayList<Organiza>();
			organizaLists = organizaService.getOrganizaByCity(contractCity);
			// 获取生成组织架构字符串
			flag = Constants.getOrganizaTree(organizaLists);

			// 实例化 page分页对象
			page = new PageBean(currentPage == 0 ? 1 : currentPage, 10);
			list = contractListService.findContractList(page, contractlist);
			if (null != list) {
				for (int i = 0; i < list.size(); i++) {
					String organizaListsid = list.get(i)
							.getContractDepartment();
					list.get(i).setContractDepartment(
							getOrganize(organizaListsid));
					// String contractUser = list.get(i).getContractor();
					// UserInfo userinfo =
					// userInfoService.getUserInfo(Integer.parseInt(contractUser));
					// String userName =
					// userinfo.getUserName()==null?"":userinfo.getUserName();
					// if(userName!=null&&!"".equals(userName))
					// {
					// list.get(i).setContractor(userName);
					// }
					String userName = list.get(i).getContractOffice() == null ? ""
							: list.get(i).getContractOffice();
					list.get(i).setContractor(userName);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			if (log.isInfoEnabled()) {
				log
						.error(
								"Exception ContractListAction findAllContractList() method",
								e);
			}
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction findAllContractList() method, return String");
		}
		return SUCCESS;
	}

	/*
	 * 删除合同
	 */
	public String deleteContract() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction deleteContract() method, return String");
		}
		// response 对象
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		// 获取PrintWriter对象
		try {
			ServletActionContext.getRequest().setCharacterEncoding(
					Constants.STR_UTF);
			response.setContentType(Constants.STR_CHARSET);
			out = response.getWriter();
		} catch (Exception e1) {
			e1.printStackTrace();
			return ERROR;
		}
		try {
			contractID = URLDecoder.decode(contractID, "UTF-8");
			HttpServletRequest request = ServletActionContext.getRequest();
			String path = request.getSession().getServletContext().getRealPath(
					"/");

			List<Contract> listContract = contractListService
					.isEixstContractID(contractID, null);
			if (null != listContract && listContract.size() > 0) {
				List<String> listMedia = new ArrayList<String>();
				listMedia = contractListService.seclectMediaName(contractID);

				if (null != listMedia && listMedia.size() > 0) {
					out.print("Nosuccess");
				} else {
					/**
					 * 删除文件和合同
					 */
					List<Contract> listContract1 = contractListService
							.isEixstContractID(contractID, null);

					contractListService.deleteContract(contractID);

					if (null != listContract1 && listContract1.size() > 0) {
						String realpath = path + getText("contract.file.path")
								+ listContract1.get(0).getContractFilename();
						File willdelFile = new File(realpath);
						if (willdelFile.exists() && willdelFile.isFile()) {
							willdelFile.delete();
						}
					}
					/*
					 * 日志记录
					 */

					// 日志记录
					UserInfo userSession = (UserInfo) ServletActionContext
							.getRequest().getSession().getAttribute("logUser");
					String user = null;
					String cityCode = null;
					String cityName = null;
					String organizaOragName = null;
					user = userSession.getUserName() == null ? "" : userSession
							.getUserName();
					cityCode = userSession.getUsercity() == null ? ""
							: userSession.getUsercity();
					cityName = userSession.getCityName() == null ? ""
							: userSession.getCityName();
					organizaOragName = userSession.getOrganiza().getOrgName() == null ? ""
							: userSession.getOrganiza().getOrgName();

					Timestamp d = new Timestamp(System.currentTimeMillis());
					String content = d + " " + cityName + organizaOragName
							+ user + "删除合同";
					String datatime = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
					/** 获取变更记录的数据 */
					Log logRecord = new Log("T_CB_CONTRACT", content,
							contractID, datatime, user, cityCode,
							organizaOragName, "科室");
					optLogService.addLog(logRecord);
					out.print("success");
				}
			} else {
				/**
				 * 提示框
				 */
				out.print("isDelete");
			}
		} catch (Exception e) {
			out.print("error");
			log
					.error(
							"Error ContractListAction deleteContract() method,return String",
							e);
			e.printStackTrace();

		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction deleteContract() method, return String");
		}
		return null;
	}

	/*
	 * 跳转到新增页面
	 */
	public String turnToAddContract() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction turnToAddContract() method, return String");
		}
		try {
			nowDate = getYearMonth();
			// System.out.println("nowDate==========>"+nowDate);

			getDictionary(); // 获取字典表中的数据
			// 查询组织架构信息 获取当前节点集合

			// 获取userSession
			UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
					.getSession().getAttribute("logUser");
			String range = null;
			String cityCode = null;
			range = userSession.getUserRole().getRoleRange() == null ? ""
					: userSession.getUserRole().getRoleRange();
			cityCode = userSession.getUsercity() == null ? "" : userSession
					.getUsercity();
			organizaLists = new ArrayList<Organiza>();
			organizaLists = organizaService.getOrganizaByCity(cityCode);
			// for (int i = 0; i < organizaLists.size(); i++) {
			// System.out.println(cityCode+"__"+organizaLists.get(i).getOrgCode()+"___"+organizaLists.get(i).getOrgName());
			// }
			// 获取生成组织架构字符串
			flag = Constants.getOrganizaTree(organizaLists);
			// 设置权限l
			dataListUSER = new ArrayList<UserInfo>();
			dataListCITY = DatadicContext.getInstance().getDicDataListByCode(
					"CITY");// 归属地市
			dataListCITY.clear();
			Dictionary date = DatadicContext.getInstance().getDatadicObject(
					cityCode, "CITY");
			dataListCITY.add(date);
			contractCity = cityCode;

		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction turnToAddContract() method, return String");
		}
		return SUCCESS;
	}

	/*
	 * 保存合同
	 */
	public String saveContract() {
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction saveContract() method, return String");
		}
		String contractFileFormat = null;
		// response 对象
		try {
			// 上传文件开始
			if (null != inputfile) {
				HttpServletRequest request = ServletActionContext.getRequest();
				String path = request.getSession().getServletContext()
						.getRealPath("/");
				Constants.upload(inputfile, inputfileFileName, path
						+ getText("contract.file.path")); // 上传文件
				contractFileFormat = getFileSuffixName(inputfileFileName); // 获取文件后缀名

				String willReNameFilepath = path
						+ getText("contract.file.path") + inputfileFileName;
				String reNameFilepath = path + getText("contract.file.path")
						+ contract.getContractID() + "." + contractFileFormat;
				File willFile = new File(willReNameFilepath);
				willFile.renameTo(new File(reNameFilepath)); // 文件重命名
				String saveFileName = contract.getContractID() + "."
						+ contractFileFormat;
				contract.setContractFilename(saveFileName == null ? ""
						: saveFileName);// 获取文件名
				contract.setContractFileFormat(contractFileFormat == null ? ""
						: contractFileFormat);// 获取后缀名
			}
			String thisYear = this.getYear();
			contract.setContractYear(thisYear);// 获取当前年度

			String contorUserID = contract.getContractor() == null ? ""
					: contract.getContractor(); // 保存用戶的汉字名字
			String contorUserName = userInfoService.getUserInfo(
					Integer.parseInt(contorUserID)).getUserName();
			contract.setContractOffice(contorUserName == null ? ""
					: contorUserName);
			contract.setContractBudget(1000);
			contract.setContractBudgetCode("");

			contractListService.addContract(contract);

			// 日志记录
			UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
					.getSession().getAttribute("logUser");
			String user = null;
			String cityCode = null;
			String cityName = null;
			String organizaOragName = null;
			user = userSession.getUserName() == null ? "" : userSession
					.getUserName();
			cityCode = userSession.getUsercity() == null ? "" : userSession
					.getUsercity();
			cityName = userSession.getCityName() == null ? "" : userSession
					.getCityName();
			organizaOragName = userSession.getOrganiza().getOrgName() == null ? ""
					: userSession.getOrganiza().getOrgName();

			Timestamp d = new Timestamp(System.currentTimeMillis());
			String content = d + " " + cityName + organizaOragName + user
					+ "创建合同";
			String datatime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
					.format(new Date());
			/** 获取变更记录的数据 */
			Log logRecord = new Log("T_CB_CONTRACT", content, contract
					.getContractID(), datatime, user, cityCode,
					organizaOragName, "科室");
			optLogService.addLog(logRecord);

			/**
			 * 提示框
			 */
			this.alertMessage("保存合同成功", "contractlist.action");

		} catch (Exception e) {
			log.error("Exception ContractListAction saveContract() method", e);
			e.printStackTrace();
			return ERROR;
		}
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction saveContract() method, return String");
		}
		return null;
	}

	/*
	 * 跳转到编辑页面
	 */
	public String turnToContractModify() {
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction turnToContractModify() method, return String");
		}
		try {
			contractID = URLDecoder.decode(contractID, "UTF-8");
			getDictionary(); // 获取字典表中的数据
			contractModify = contractListService.detailContract(contractID);
			if (null != contractModify) {
				String organizaListsid = null;
				organizaListsid = contractModify.getContractDepartment() == null ? ""
						: contractModify.getContractDepartment();

				// 显示部门科室
				String contractUser = contractModify.getContractor();
				String department = contractModify.getContractDepartment();

				dataListUSER = new ArrayList<UserInfo>();
				dataListUSER = userInfoService.getUserInfoByOrgCode(department);

				contractModify.setContractor(contractUser);
				contractDepartmentName = getOrganize(organizaListsid);

				// 获取userSession
				UserInfo userSession = (UserInfo) ServletActionContext
						.getRequest().getSession().getAttribute("logUser");
				String range = null;
				String cityCode = null;
				range = userSession.getUserRole().getRoleRange() == null ? ""
						: userSession.getUserRole().getRoleRange();
				cityCode = userSession.getUsercity() == null ? "" : userSession
						.getUsercity();

				// 查询组织架构信息 获取当前节点集合
				organizaLists = new ArrayList<Organiza>();
				organizaLists = organizaService.getOrganizaByCity(cityCode);
				// 获取生成组织架构字符串
				flag = Constants.getOrganizaTree(organizaLists);
				// 设置权限
				dataListCITY = DatadicContext.getInstance()
						.getDicDataListByCode("CITY");// 归属地市
				dataListCITY.clear();
				Dictionary date = DatadicContext.getInstance()
						.getDatadicObject(cityCode, "CITY");
				dataListCITY.add(date);
				contractCity = cityCode;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction turnToContractModify() method, return String");
		}
		return SUCCESS;
	}

	/*
	 * 保存编辑后的修改页面
	 */

	public String updataModifyContract() {
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction updataModifyContract() method, return String");
		}
		String contractFileFormat = null;
		try {
			String idcontor = contractUpdataModify.getContractID();
			List<Contract> listContract02 = contractListService
					.isEixstContractID(idcontor, null);
			if (null != listContract02 && listContract02.size() > 0) {
				// 上传文件开始
				if (null != inputfile) {
					HttpServletRequest request = ServletActionContext
							.getRequest();
					String path = request.getSession().getServletContext()
							.getRealPath("/");
					String contractIdString = contractUpdataModify
							.getContractID();
					List<Contract> listContract = contractListService
							.isEixstContractID(contractIdString, null);

					// 删除文件
					if (null != listContract && listContract.size() > 0) {
						String realpath = path + getText("contract.file.path")
								+ listContract.get(0).getContractFilename();
						File willdelFile = new File(realpath);
						if (willdelFile.exists() && willdelFile.isFile()) {
							willdelFile.delete();
						}
					}

					// 上传文件
					Constants.upload(inputfile, inputfileFileName, path
							+ getText("contract.file.path"));
					contractFileFormat = getFileSuffixName(inputfileFileName);
					String willReNameFilepath = path
							+ getText("contract.file.path") + inputfileFileName;
					String reNameFilepath = path
							+ getText("contract.file.path")
							+ contractUpdataModify.getContractID() + "."
							+ contractFileFormat;
					File willFile = new File(willReNameFilepath);
					willFile.renameTo(new File(reNameFilepath)); // 文件重命名
					String saveFileName = contractUpdataModify.getContractID()
							+ "." + contractFileFormat;
					contractUpdataModify.setContractFilename(saveFileName);// 获取文件名
					contractUpdataModify
							.setContractFileFormat(contractFileFormat);// 获取后缀名
				}

				String thisYear = this.getYear();
				contractUpdataModify.setContractYear(thisYear);// 获取当前年度

				String contorUserID = contractUpdataModify.getContractor() == null ? ""
						: contractUpdataModify.getContractor(); // 保存用戶的汉字名字
				String contorUserName = userInfoService.getUserInfo(
						Integer.parseInt(contorUserID)).getUserName();
				contractUpdataModify
						.setContractOffice(contorUserName == null ? ""
								: contorUserName);
				contractUpdataModify.setContractBudget(1000);
				contractUpdataModify.setContractBudgetCode("");

				contractListService.updataContract(contractUpdataModify);

				// 日志记录
				UserInfo userSession = (UserInfo) ServletActionContext
						.getRequest().getSession().getAttribute("logUser");
				String user = null;
				String cityCode = null;
				String cityName = null;
				String organizaOragName = null;
				user = userSession.getUserName() == null ? "" : userSession
						.getUserName();
				cityCode = userSession.getUsercity() == null ? "" : userSession
						.getUsercity();
				cityName = userSession.getCityName() == null ? "" : userSession
						.getCityName();
				organizaOragName = userSession.getOrganiza().getOrgName() == null ? ""
						: userSession.getOrganiza().getOrgName();

				Timestamp d = new Timestamp(System.currentTimeMillis());
				String content = d + " " + cityName + organizaOragName + user
						+ "修改合同";
				String datatime = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
				/** 获取变更记录的数据 */
				Log logRecord = new Log("T_CB_CONTRACT", content,
						contractUpdataModify.getContractID(), datatime, user,
						cityCode, organizaOragName, "科室");
				optLogService.addLog(logRecord);

				this.alertMessage("合同修改成功", "contractlist.action");
			} else {
				return ERROR;
			}
		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log
						.error(
								"Exception ContractListAction updataModifyContract() method",
								e);
			}
			e.printStackTrace();
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction updataModifyContract() method, return String");
		}
		return SUCCESS;
	}

	/*
	 * 跳转到详情页面
	 */
	public String turnToContractDetail() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction turnToContractDetail() method, return String");
		}
		getDictionary();
		try {
			contractID = URLDecoder.decode(contractID, "UTF-8");
			toType = URLDecoder.decode(toType, "UTF-8");
			HttpServletRequest request = ServletActionContext.getRequest();
			String realFilePath = request.getSession().getServletContext()
					.getRealPath("/");

			// listMediaName = contractListService.seclectMediaName(contractID);
			listMediaPrice = contractListService.seclectMediaPrice(contractID);
			contractDetail = contractListService.detailContract(contractID);
			if (null != contractDetail) {
				String filename = realFilePath + getText("contract.file.path")
						+ contractDetail.getContractFilename();
				GetFileSizes getfile = new GetFileSizes();
				String fis = getfile.fileSize(filename);
				if (null == fis) {
					contractFileSize = "(" + "0K" + ")";
				} else {
					contractFileSize = "(" + fis + ")"; // 获取文件大小
				}

				// contractDetail.getContractBudget();
				// contractDetail.setContractBudget(contractDetail.getContractBudget()
				// / 10000);// 转化为万元
				conuml = 16 - listMediaPrice.size();
				String organizaListsid = contractDetail.getContractDepartment();
				contractDetail
						.setContractDepartment(getOrganize(organizaListsid));
				String contractUser = contractDetail.getContractor();
				UserInfo userinfo = userInfoService.getUserInfo(Integer
						.parseInt(contractUser));
				if (null != userinfo) {
					contractDetail.setContractor(userinfo.getUserName());
				} else {
					contractDetail.setContractor(contractDetail
							.getContractOffice());
				}
				Log sample = new Log();
				sample.setRelationId(contractDetail.getContractID());
				sample.setLogType("T_CB_CONTRACT");
				logList = new ArrayList<Log>();
				logList = optLogService.getLogsBySample(sample);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction turnToContractDetail() method, return String");
		}
		return SUCCESS;
	}

	/**
	 * 判读是否已经存在此合同编号
	 * 
	 * @return
	 */
	public String isExistContractID() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter UserAction isExistContractID() method,return String");
		}
		// response 对象
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			// 获取PrintWriter对象
			ServletActionContext.getRequest().setCharacterEncoding(
					Constants.STR_UTF);
			response.setContentType(Constants.STR_CHARSET);
			out = response.getWriter();
			if (null != contract.getContractID()
					|| !"".equals(contract.getContractID())) {
				String getContractID = URLDecoder.decode(contract
						.getContractID(), "UTF-8");
				// 查询
				List<Contract> listContract = contractListService
						.isEixstContractID(getContractID, null);
				if (null != listContract && listContract.size() > 0) {
					out.print("success");
				}
			}
		} catch (Exception e) {
			log
					.error(
							"Error UserAction isExistContractID() method,return String",
							e);
			e.printStackTrace();
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit UserAction isExistContractID() method,return String");
		}
		return null;
	}

	/**
	 * 判读是否已经存在此合同名称
	 * 
	 * @return
	 */
	public String isExistContractName() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter UserAction isExistContractID() method,return String");
		}
		// response 对象
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			// 获取PrintWriter对象
			ServletActionContext.getRequest().setCharacterEncoding(
					Constants.STR_UTF);
			response.setContentType(Constants.STR_CHARSET);
			out = response.getWriter();
			if (null != contract.getContractName()
					|| !"".equals(contract.getContractName())) {
				String getContractName = URLDecoder.decode(contract
						.getContractName(), "UTF-8");
				// 查询
				List<Contract> listContract = contractListService
						.isEixstContractID(null, getContractName);
				if (null != listContract && listContract.size() > 0) {
					UserInfo userSession = (UserInfo) ServletActionContext
							.getRequest().getSession().getAttribute("logUser");
					String contractNowCity = userSession.getUsercity() == null ? ""
							: userSession.getUsercity();
					String contractNowYear = this.getYear();
					for (int i = 0; i < listContract.size(); i++) {
						String contractYe = listContract.get(i)
								.getContractYear();
						String contractCi = listContract.get(i)
								.getContractCity();
						if (contractCi.equals(contractNowCity)
								&& contractYe.equals(contractNowYear)) {
							out.print("success");
							return null;
						}
					}
				}
			}
		} catch (Exception e) {
			log
					.error(
							"Error UserAction isExistContractID() method,return String",
							e);
			e.printStackTrace();
			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit UserAction isExistContractID() method,return String");
		}
		return null;
	}

	// 获取组织架构的签约人
	public String getContractUser() {
		// response 对象
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			// 获取PrintWriter对象
			ServletActionContext.getRequest().setCharacterEncoding(
					Constants.STR_UTF);
			response.setContentType(Constants.STR_CHARSET);
			out = response.getWriter();
			if (null != contract.getContractDepartment()
					&& !"".equals(contract.getContractDepartment())) {
				String contractorDepartment = URLDecoder.decode(contract
						.getContractDepartment(), "UTF-8");
				dataListUSER = new ArrayList<UserInfo>();
				dataListUSER = userInfoService
						.getUserInfoByOrgCode(contractorDepartment);
				Map map = new HashMap<Object, Object>();
				map.put("dataListUSER", dataListUSER);
				JSONArray jo = JSONArray.fromObject(map);
				out.print(jo.toString());
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return null;
	}

	/**
	 * 获取地市下的组织架构
	 * 
	 * @return
	 */
	public String getOrganization() {
		// response 对象
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			// 获取PrintWriter对象
			ServletActionContext.getRequest().setCharacterEncoding(
					Constants.STR_UTF);
			response.setContentType(Constants.STR_CHARSET);
			out = response.getWriter();
			if (null != contractCitycode && !"".equals(contractCitycode)) {
				String contractorCityCode = URLDecoder.decode(contractCitycode,
						"UTF-8");
				// 查询组织架构信息 获取当前节点集合
				organizaLists = new ArrayList<Organiza>();
				organizaLists = organizaService
						.getOrganizaByCity(contractorCityCode);
				// 获取生成组织架构字符串
				String flagstr = Constants.getOrganizaTree(organizaLists);
				Map map = new HashMap<Object, Object>();
				map.put("flagstr", flagstr);

				JSONArray jo = JSONArray.fromObject(map);
				out.print(jo.toString());
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String down() throws Exception {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log.info("Enter UserAction down() method,return String");
		}
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String path = request.getSession().getServletContext().getRealPath(
					"/");
			fileName = URLDecoder.decode(fileName, "UTF-8");
			String realpath = path + getText("contract.file.path") + fileName;
			System.out.println(realpath);
			file = new File(realpath);
			// 判断文件路径是否存在文件，如果不存在直接返回异常
			if (!file.exists()) {
				return null;
			}
			// 中文文件名转码
			fileName = new String(fileName.getBytes(), "ISO8859-1");
			// 下载流
			downloadStream = new FileInputStream(realpath);
		} catch (Exception e) {
			e.printStackTrace();

			return ERROR;
		}
		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log.info("Exit UserAction down() method,return String");
		}
		return "export_download";
	}

	/**
	 * 弹出提示信息
	 */
	private void alertMessage(String message, String url) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			out = response.getWriter();
			out.println(" <script type='text/javascript' >");
			out.println("alert('" + message + "');");
			out.println("location='" + url + "'");
			out.println(" </script>");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取组织架构中的数据
	 */

	public String getOrganize(String organizaListsid) {
		List<Organiza> organizaL = new ArrayList<Organiza>();
		Organiza organiza = new Organiza();
		organiza.setOrgCode(organizaListsid);
		// 查询组织架构信息 获取当前节点集合
		organizaL = organizaService.getOrganizas(organiza);
		String orgName = null;
		orgName = organizaL.get(0).getOrgName() == null ? "" : organizaL.get(0)
				.getOrgName();
		return orgName;
	}

	/**
	 * 返回当前年月日
	 * 
	 * @return
	 */
	public String getYear() {
		Calendar cal = Calendar.getInstance();
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy");
		Calendar c = Calendar.getInstance();
		c.set(c.DATE, 1);
		return df.format(c.getTime());
	}

	/**
	 * 返回当前年月日
	 * 
	 * @return
	 */
	private String getYearMonth() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
				"yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		return df.format(c.getTime());
	}

	/*
	 * 获取字典表中的数据
	 */
	public void getDictionary() {
		dataListGYSLX = DatadicContext.getInstance().getDicDataListByCode(
				"GYSLX"); // 供应商类型
		if (dataListGYSLX == null) {
			dataListGYSLX = new ArrayList<Dictionary>();
		}
		dataListHTLX = DatadicContext.getInstance()
				.getDicDataListByCode("HTLX");// 合同类型
		if (dataListHTLX == null) {
			dataListHTLX = new ArrayList<Dictionary>();
		}
		dataListQYJB = DatadicContext.getInstance()
				.getDicDataListByCode("QYJB");// 签约级别
		if (dataListQYJB == null) {
			dataListQYJB = new ArrayList<Dictionary>();
		}
		dataListCITY = DatadicContext.getInstance()
				.getDicDataListByCode("CITY");// 归属地市
		if (dataListCITY == null) {
			dataListCITY = new ArrayList<Dictionary>();
		}
		dataListFKFS = DatadicContext.getInstance()
				.getDicDataListByCode("FKFS");// 付款方式
		if (dataListFKFS == null) {
			dataListFKFS = new ArrayList<Dictionary>();
		}
	}

	/*
	 * 截取字符串,获取文件的后缀名
	 */
	private String getFileSuffixName(String fileName) {
		int suffix = fileName.lastIndexOf(".") + 1;
		String filesuffixName = fileName.substring(suffix, fileName.length());
		return filesuffixName;

	}

	/**
	 * 属性的set/get方法
	 * 
	 * @return
	 */
	public Contract getContract() {
		return contract;
	}

	public void setContract(Contract contract) {
		this.contract = contract;
	}

	public List<Dictionary> getDataListGYSLX() {
		return dataListGYSLX;
	}

	public void setDataListGYSLX(List<Dictionary> dataListGYSLX) {
		this.dataListGYSLX = dataListGYSLX;
	}

	public List<Dictionary> getDataListHTLX() {
		return dataListHTLX;
	}

	public void setDataListHTLX(List<Dictionary> dataListHTLX) {
		this.dataListHTLX = dataListHTLX;
	}

	public List<Dictionary> getDataListQYJB() {
		return dataListQYJB;
	}

	public void setDataListQYJB(List<Dictionary> dataListQYJB) {
		this.dataListQYJB = dataListQYJB;
	}

	public List<Dictionary> getDataListCITY() {
		return dataListCITY;
	}

	public void setDataListCITY(List<Dictionary> dataListCITY) {
		this.dataListCITY = dataListCITY;
	}

	public List<Dictionary> getDataListFKFS() {
		return dataListFKFS;
	}

	public void setDataListFKFS(List<Dictionary> dataListFKFS) {
		this.dataListFKFS = dataListFKFS;
	}

	public ContractListService getContractListService() {
		return contractListService;
	}

	public void setContractListService(ContractListService contractListService) {
		this.contractListService = contractListService;
	}

	public List<Contract> getList() {
		return list;
	}

	public void setList(List<Contract> list) {
		this.list = list;
	}

	public String getInputKeyword() {
		return inputKeyword;
	}

	public void setInputKeyword(String inputKeyword) {
		this.inputKeyword = inputKeyword;
	}

	public int getKeyword() {
		return keyword;
	}

	public void setKeyword(int keyword) {
		this.keyword = keyword;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public PageBean getPage() {
		return page;
	}

	public void setPage(PageBean page) {
		this.page = page;
	}

	public String getYears() {
		return years;
	}

	public void setYears(String years) {
		this.years = years;
	}

	public List<Contract> getYearsList() {
		return yearsList;
	}

	public void setYearsList(List<Contract> yearsList) {
		this.yearsList = yearsList;
	}

	public File getInputfile() {
		return inputfile;
	}

	public void setInputfile(File inputfile) {
		this.inputfile = inputfile;
	}

	public String getInputfileFileName() {
		return inputfileFileName;
	}

	public void setInputfileFileName(String inputfileFileName) {
		this.inputfileFileName = inputfileFileName;
	}

	public String getInputfileContentType() {
		return inputfileContentType;
	}

	public void setInputfileContentType(String inputfileContentType) {
		this.inputfileContentType = inputfileContentType;
	}

	public String getContractID() {
		return contractID;
	}

	public void setContractID(String contractID) {
		this.contractID = contractID;
	}

	public Contract getContractDetail() {
		return contractDetail;
	}

	public void setContractDetail(Contract contractDetail) {
		this.contractDetail = contractDetail;
	}

	public Contract getContractModify() {
		return contractModify;
	}

	public void setContractModify(Contract contractModify) {
		this.contractModify = contractModify;
	}

	public String getContractFileSize() {
		return contractFileSize;
	}

	public void setContractFileSize(String contractFileSize) {
		this.contractFileSize = contractFileSize;
	}

	public Contract getContractUpdataModify() {
		return contractUpdataModify;
	}

	public void setContractUpdataModify(Contract contractUpdataModify) {
		this.contractUpdataModify = contractUpdataModify;
	}

	public List<String> getListMediaName() {
		return listMediaName;
	}

	public void setListMediaName(List<String> listMediaName) {
		this.listMediaName = listMediaName;
	}

	public Integer getConuml() {
		return conuml;
	}

	public void setConuml(Integer conuml) {
		this.conuml = conuml;
	}

	public String getContractLevel() {
		return contractLevel;
	}

	public void setContractLevel(String contractLevel) {
		this.contractLevel = contractLevel;
	}

	public String getContractCity() {
		return contractCity;
	}

	public void setContractCity(String contractCity) {
		this.contractCity = contractCity;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getDownloadStream() {
		return downloadStream;
	}

	public void setDownloadStream(InputStream downloadStream) {
		this.downloadStream = downloadStream;
	}

	public String getNowDate() {
		return nowDate;
	}

	public void setNowDate(String nowDate) {
		this.nowDate = nowDate;
	}

	public List<Organiza> getOrganizaLists() {
		return organizaLists;
	}

	public void setOrganizaLists(List<Organiza> organizaLists) {
		this.organizaLists = organizaLists;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public OrganizaService getOrganizaService() {
		return organizaService;
	}

	public void setOrganizaService(OrganizaService organizaService) {
		this.organizaService = organizaService;
	}

	public String getContractOrganize() {
		return contractOrganize;
	}

	public void setContractOrganize(String contractOrganize) {
		this.contractOrganize = contractOrganize;
	}

	public String getOrganizeValue() {
		return organizeValue;
	}

	public void setOrganizeValue(String organizeValue) {
		this.organizeValue = organizeValue;
	}

	public OptLogService getOptLogService() {
		return optLogService;
	}

	public void setOptLogService(OptLogService optLogService) {
		this.optLogService = optLogService;
	}

	public List<Log> getLogList() {
		return logList;
	}

	public void setLogList(List<Log> logList) {
		this.logList = logList;
	}

	public List<UserInfo> getDataListUSER() {
		return dataListUSER;
	}

	public void setDataListUSER(List<UserInfo> dataListUSER) {
		this.dataListUSER = dataListUSER;
	}

	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getContractDepartmentName() {
		return contractDepartmentName;
	}

	public void setContractDepartmentName(String contractDepartmentName) {
		this.contractDepartmentName = contractDepartmentName;
	}

	public String getContractCitycode() {
		return contractCitycode;
	}

	public void setContractCitycode(String contractCitycode) {
		this.contractCitycode = contractCitycode;
	}

	public List<MediaPrice> getListMediaPrice() {
		return listMediaPrice;
	}

	public void setListMediaPrice(List<MediaPrice> listMediaPrice) {
		this.listMediaPrice = listMediaPrice;
	}

	public String getToType() {
		return toType;
	}

	public void setToType(String toType) {
		this.toType = toType;
	}

}
